package com.qf.web.servlet;

import com.alibaba.fastjson.JSON;
import com.qf.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@WebServlet("/test")
public class TestServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        String id = req.getParameter("id");
//        String username = req.getParameter("username");
//        System.out.println(id + "::" + username);

        //获取  字符流缓冲区
        BufferedReader reader = req.getReader();

        String str = reader.readLine();
        System.out.println("从前端传过来的数据："+str);
        User user = JSON.parseObject(str, User.class);
        System.out.println(user);


        System.out.println("post请求已执行");


        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write("post访问成功");

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String id = req.getParameter("id");
        String username = req.getParameter("username");
        System.out.println(id + "::" + username);

        User user = new User(Integer.parseInt(id), username, '男', "北京北科");

//        System.out.println("get请求已执行");

        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();
        String json = JSON.toJSONString(user);
        writer.write(json);

        // TODO
    }
}
